package com.enjoyor.soa.traffic.util.mina;

import java.util.ArrayList;
import java.util.List;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class CharsetDecoder implements ProtocolDecoder {
    @SuppressWarnings({ "unchecked", "rawtypes" })
    private ArrayList<Byte> list = new ArrayList();

    public CharsetDecoder() {
    }

    public byte[] listToByte(List<Byte> list) {
        byte[] b = new byte[list.size()];

        for (int i = 0; i < list.size(); ++i) {
            b[i] = (Byte) list.get(i);
        }

        return b;
    }

    public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
        IoBuffer.allocate(8).setAutoExpand(true);

        while (in.hasRemaining()) {
            byte b = in.get();
            this.list.add(b);
        }

        byte[] bytes = this.listToByte(this.list);
        out.write(IoBuffer.wrap(bytes));
    }

    public void dispose(IoSession arg0) throws Exception {
    }

    public void finishDecode(IoSession arg0, ProtocolDecoderOutput arg1) throws Exception {
    }
}
